#!/bin/bash

function usage() {
    echo "Usage: $0 [input_dir]"
    echo "Import all images from directory's *.tar.gz to k8s.io namespace"
    exit 1
}

# waring this operation will clear target dir
if [ "$#" -gt 1 ]; then
    usage
fi

# show warning and waiting user input

# check if ctr is installed
if ! command -v ctr &> /dev/null
then
    echo "ctr is not installed. Please install ctr and try again."
    exit 1
fi


# from args then default to current dir's subdir images
INPUT_DIR=$1

# check if output dir exists
if [ ! -d "$INPUT_DIR" ]; then
    echo "$INPUT_DIR  Input directory does not exist. Please create it and try again."
    exit 1
fi


IMAGES=$(ls -1 "$INPUT_DIR"/*.tar 2>/dev/null )

for image in $IMAGES; do
    echo "Import image: $image"
    # import
    ctr -n k8s.io i import "$image"
done

echo "Images imported from $INPUT_DIR total count: ${IMAGES[@]}"